<?php

class InventoryitemController extends Zend_Controller_Action
{

	public function indexAction()
	{
		$this->_redirect('mpcmapping/view');
	}
	
	public function viewAction()
	{
 		$this->view->pageTitle = 'List all MasterCode Mappings';
 		
 		$dbcon = Zend_Db_Table::getDefaultAdapter();
 		
 		$this->view->entries = $dbcon->fetchAll("SELECT i.inventoryItem, i.masterCode, im.inventoryItemDesc, mpc.masterCodeDesc  FROM bis.tbl_inventoryitemmpcmapping i 
 													LEFT JOIN bis.tbl_inventoryItem im ON im.inventoryItem=i.inventoryItem
 													LEFT JOIN bis.tbl_hyperionProductRollup mpc ON i.masterCode = mpc.mastercode");
	}
	
	public function addAction()
	{
 		$request = $this->getRequest();
 		$form = new Application_Form_InventoryItemAddMapping();
 	
 		if($request->isPost()) {
 			if ($form->isValid($request->getPost())) {
				
 				$dbcon = Zend_Db_Table::getDefaultAdapter();
 				
 				$dbcon->insert('bis.tbl_inventoryItemmpcmapping', array('inventoryItem' => $form->getValue('inventoryItem'), 'masterCode' => $form->getValue('masterCode')));
 				
 				$dbcon->query("call updateInventoryItem();");
 	
 				$this->_redirect('inventoryitem/view');
 			}
 	
 		}
 		$form->getElement('submit')->setLabel('Add');
 		$form->setAction('add');
 		$this->view->pageTitle = "Add new MPC mapping";
 		$this->view->form = $form;
		
	}
	
	public function editAction()
	{
		$request = $this->getRequest();
		$form = new Application_Form_InventoryItemAddMapping();
	
		if($request->isPost()) {
			if ($form->isValid($request->getPost())) {
	
	
				$dbcon = Zend_Db_Table::getDefaultAdapter();
					
				$dbcon->update('bis.tbl_inventoryItemmpcmapping', array('inventoryItem' => $form->getValue('inventoryItem'), 'masterCode' => $form->getValue('masterCode')),'inventoryItem=\''.$form->getValue('inventoryItem').'\'');
				
				$dbcon->query("call updateInventoryItem();");
				
				$this->_redirect('inventoryitem/view');
			}
	
		}
		else {
			
			$param = $request->getParams(); //get inventoryItem

			if ($param['sku'] == null)
			{
				die;
			}
			else {
				$dbcon = Zend_Db_Table::getDefaultAdapter();

				$mpc = $dbcon->fetchRow("SELECT inventoryItem, masterCode FROM bis.tbl_inventoryItemMPCMapping WHERE inventoryItem='".$param['sku']."'");
				
				$form->setAction('../../edit');
				$form->getElement('submit')->setLabel('Change');
				$form->getELement('inventoryItem')->setAttrib('readonly', 'readonly');
				$form->populate($mpc);
			}
		}
		
		$this->view->pageTitle = "Edit MPC mapping";
		$this->view->form = $form;
			
	}
	
	public function deleteAction()
	{
		//$dbconn = new Application_Model_DbTable_Salesrepname();
		//$dbconn->delete('id='.$this->getRequest()->getParam('id'));

	}
	
}

